package com.fuyun.microservice.handler;


import com.fuyun.microservice.codec.msg.Header;
import com.fuyun.microservice.codec.msg.LoginResponseMessage;
import com.fuyun.microservice.codec.msg.Message;
import com.fuyun.microservice.utils.Constants;
import com.fuyun.microservice.utils.SessionState;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class AuthAbstractHandler<T extends Message> extends SimpleChannelInboundHandler<T> {

    /**
     * 校验channel是否已登录
     * @param ctx
     * @param msg
     * @throws InterruptedException
     */
    protected final void channelAuth(ChannelHandlerContext ctx,T msg ) throws InterruptedException {
        Channel ch = ctx.channel();
        boolean isLogin = SessionState.LOGIN.equals(ch.attr(Constants.attributeKey).get());
        if (!isLogin) {
            log.warn("channel {} not login, force close", ch);
            Header header = msg.getHeader();
            LoginResponseMessage loginResponseMessage = new LoginResponseMessage(header.getSequenceNo());
            loginResponseMessage.setRspCode(0);
            loginResponseMessage.setRspMessage("please login");
            ctx.writeAndFlush(loginResponseMessage);

            Thread.sleep(50L);
            ctx.channel().close();
            ctx.fireChannelReadComplete();
        }
    }

}
